<template>
  <div class="content-view">
    <!-- 工具栏 -->
    <div class="tool-bar">
      <div class="view">
        <el-input placeholder="按项目单编号筛选" v-model="searchKey.words" clearable>
          <template #suffix>
            <i class="iconfont icon-sousuo"></i>
          </template>
        </el-input>
        <!-- 条件搜索 -->
        <condition-query :data="data" @search="searchDone" />
      </div>
      <div class="view end">
        <!-- <el-button type="primary" @click="handleBtn(0, {name: ''}, 'add')" v-if="user.power*1 == 99 && data.id=='device_factory'">
          <i class="iconfont icon-kehuguanli"></i>新建设备[测试]
        </el-button> -->
        <el-button :type="devPage.batchColor" @click="handleBatch" v-if="devPage.batchShow">
          <i class="iconfont icon-jurassic_batch-work"></i>{{devPage.batchBtn}}
        </el-button>
        <!-- <el-button type="danger" @click="handleBatch('uninstall')" v-if="devPage.flag == 'device_app'">
          <i class="iconfont icon-jurassic_batch-work"></i>卸载应用
        </el-button>
        <el-button type="primary" @click="handleBatch('autorun')" v-if="devPage.flag == 'device_app'">
          <i class="iconfont icon-jurassic_batch-work"></i>设置开机启动
        </el-button> -->
      </div>
    </div>
    <!-- 表格 -->
    <el-table 
      :data="deviceList.filter(data => !searchKey.words || data.project_list_number.toLowerCase().includes(searchKey.words.toLowerCase()))"
      border stripe
      v-loading="loading" 
      :default-sort="{prop: 'dtCreate', order: 'ascending'}"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center"/>
      <el-table-column prop="on_offline" label="设备状态" sortable width="120"  :show-overflow-tooltip="true" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.on_offline==1?'success':'info'">
            {{scope.row.on_offline==1?'在线':'离线'}}
          </el-tag> 
        </template>
      </el-table-column>
      <el-table-column prop="sn" label="设备序列号" sortable width="180" :show-overflow-tooltip="true"> 
        <template #default="scope">
          <el-tag :type="scope.row.status == 0?'success':'danger'" v-if="scope.row.status < 0">
            {{scope.row.status}}
          </el-tag> 
          {{scope.row.sn}}
        </template>
      </el-table-column>
      <el-table-column prop="borad_sn" label="主板序列号" sortable width="180" :show-overflow-tooltip="true"> </el-table-column>
      <el-table-column label="项目单编号" sortable width="150" :show-overflow-tooltip="true" v-if="user.power > 90"> 
        <template #default="scope">{{scope.row.project_list_number?scope.row.project_list_number:'未设置'}}</template>
      </el-table-column>
      <el-table-column prop="plat_user.name" label="所属用户" sortable width="180" :show-overflow-tooltip="true"> </el-table-column>
      <el-table-column prop="equipment_model.model" label="设备型号" sortable width="150" :show-overflow-tooltip="true"> </el-table-column>
      <el-table-column v-if="data.id != 'device_factory'" prop="current_version" label="当前固件版本" sortable width="150" :show-overflow-tooltip="true"> </el-table-column>
      <el-table-column v-if="data.id != 'device_factory'" prop="dtExfactory" label="出厂日期" sortable width="180"> </el-table-column>
      <el-table-column label="操作" fixed="right" width="150" align="center" v-if="user.power*1 == 99 && data.id=='device_list'" prop="project_list_number" sortable>
        <template #default="scope">
          <el-tag v-if="isNull(scope.row.project_list_number)" type="danger">尚未进行出厂设置</el-tag>
          <el-button v-else type="danger" size="small" @click="handleBtn(scope.$index, scope.row, 'factory')">恢复未出厂状态</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="100" align="center" v-if="user.power*1 == 99 && data.id=='device_factory'">
        <template #default="scope">
          <el-button v-if="isNull(scope.row.borad_sn)" type="success" size="small" @click="handleBtn(scope.$index, scope.row, 'bind')">绑定主板</el-button>
          <el-button v-else type="danger" size="small" @click="handleBtn(scope.$index, scope.row, 'unbind')">解绑主板</el-button>
        </template>
      </el-table-column>
      <el-table-column v-if="data.id == 'device_app'" label="操作" fixed="right" align="center" width="220">
        <template #default="scope">
          <el-button class="row-inline" type="danger" size="small" @click="handleBtn(scope.$index, scope.row, 'uninstall')">卸载应用</el-button>
          <el-button class="row-inline" type="primary" size="small" @click="handleBtn(scope.$index, scope.row, 'autorun')">设置开机自启</el-button>
          <!-- <el-button class="row-inline" type="success" size="small" @click="handleBtn(scope.$index, scope.row, 'detail')">设备详情</el-button> -->
        </template>
      </el-table-column>
      <el-table-column v-if="data.id != 'device_app'" label="操作" fixed="right" width="100">
        <template #default="scope">
          <span class="icon-btn" @click="handleBtn(scope.$index, scope.row, 'detail')">
            <i class="iconfont icon-chakan success"></i>设备详情
          </span>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <page-div ref="PAGING_COM" @change="pageChange" />
    <!-- dialog -->
    <dev-detail ref="DEV_DETAIL"/>
    <device-dlg ref="DEV_DLG" @done="deviceDone"/>
    <batch-dev-dlg ref="BATCH_DLG" @done="deviceDone"/>
  </div>
</template>

<script>
import { getCurrentInstance, onMounted, onUnmounted, reactive, ref } from 'vue'
import ConditionQuery from '../fun_mod/ConditionQuery.vue'
import PageDiv from '../fun_mod/PageDiv.vue'
import http from '@/axios/http'
import util from '@/assets/js/util'
import mqtt from '@/assets/js/mqtt'
import BatchDevDlg from '../dialog/BatchDevDlg.vue'
import { ElNotification } from 'element-plus'
import DeviceDlg from '../dialog/DeviceDlg.vue'
import DevDetail from '../dialog/DevDetail.vue'
export default {
  components: { 
    ConditionQuery,
    PageDiv,
    BatchDevDlg,
    DeviceDlg,
    DevDetail
  },
  props:['data'],
  setup(props) {
    const Global = getCurrentInstance().proxy
    let user = reactive({
      id: Global.$var.user.id,
      username: Global.$var.user.username,
      power: Global.$var.user.power,
      clientId: Global.$var.user.clientId
    });

    let devPage = reactive({
      flag: 'device',
      batchBtn: '批量处理',
      batchColor: 'warning',
      batchShow: true,
    })

    onMounted(()=>{
      devPage.flag = props.data.id
    //console.log(devPage.flag)
      if (devPage.flag == 'device_factory') {
        devPage.batchBtn = '批量出厂设置'
      }
      if (devPage.flag == 'device_list') {
        devPage.batchShow = user.power*1 > 80
        devPage.batchBtn = '设置所属用户'
      }
      if (devPage.flag == 'device_app') {
        devPage.batchBtn = '安装应用'
        devPage.batchColor = 'success'
      }
      if (devPage.flag == 'device_system') {
        devPage.batchBtn = '系统升级或重置'
        devPage.batchColor = 'primary'
      }
      if (devPage.flag == 'device_reset') {
        devPage.batchBtn = '重启关机'
        devPage.batchColor = 'danger'
      }
      setBatchData('')
      getDevice()
      mqttOnMsg()
    })

    function mqttOnMsg() {
      mqtt.onMsg((t,m)=>{
        loading.value = false
        let r = JSON.parse(m)
        if (r.data.returnCode == 10000) {
          let d = r.data.data
          if (r.msgType == 102) {
            let devFlag = sessionStorage.getItem('DEV_FLAG')
            if (devPage.flag == devFlag) {
            //console.log(d)
              for (let i in d) {
                d[i].dtExfactory = util.formatGmt(d[i].ExfactoryDate)
              }
              deviceList.value = d
              paging.total = r.data.count
              if (PAGING_COM.value) PAGING_COM.value.setData(paging)
            }
          }
        }  
      })
    }

    let deviceList = ref([]) 
    let loading = ref(false)
    function getDevice() {
      sessionStorage.setItem('DEV_FLAG',devPage.flag)
      loading.value = true
      let msgCode = 102
      let topic = mqtt.TOPIC_REQ+msgCode
      let g = {}
      g.msgType = msgCode
      g.clientId = user.id
      g.userName = user.username
      let m = {}
      m.user_name = searchKey.user_name
      if (devPage.flag == 'device_factory') {
        // m.equipment_model = '系统默认'
        m.plat_user_id = user.clientId
        m.project_list_number = searchKey.project_list_number
      } else {
        m.equipment_model = searchKey.equipment_model
        m.project_list_number = isNull(searchKey.project_list_number)?'NO.':searchKey.project_list_number
      }
      m.sn = searchKey.sn
      m.board_sn = searchKey.board_sn
      if (!isNull(searchKey.status)) m.status = searchKey.status
      if (!isNull(searchKey.left_date)) m.left_date = searchKey.left_date
      if (!isNull(searchKey.right_date)) m.left_date = searchKey.right_date
      m.indexPage = paging.index
      m.pageSize = paging.size
      g.message = m
    //console.log('设备列表：',JSON.stringify(g))
      mqtt.publish(topic,JSON.stringify(g))
    }
    // 多选
    let batchData = []
    function handleSelectionChange(e) {
      batchData = e
      setBatchData(e)
    }

    // 分页
    let PAGING_COM = ref(null)
    let paging = reactive({
      total: 0,
      index: 1,
      size: 50
    })
    function pageChange(e) {
      paging.index = e
      getDevice()
    }
    // 搜索
    let searchKey = reactive({
      words: '',
      sn: '',
      board_sn: '',
      equipment_model: '',
      user_name: '',
      status: 0,
      left_date: '',
      right_date: '',
    })
    function searchDone(e) {
    //console.log(e)
      searchKey.words = ''
      searchKey.sn = ''
      searchKey.board_sn = ''
      searchKey.equipment_model = ''
      searchKey.user_name = ''
      searchKey.project_list_number = ''
      searchKey.status = ''
      searchKey.left_date = ''
      searchKey.right_date = ''
      e.forEach(v=>{
        if (v.t == '设备序列号') searchKey.sn = v.v
        if (v.t == '主板序列号') searchKey.board_sn = v.v
        if (v.t == '设备型号') searchKey.equipment_model = v.v
        if (v.t == '所属用户') searchKey.user_name = v.v
        if (v.t == '项目单编号') searchKey.project_list_number = v.v
        if (v.t == '状态') searchKey.status = v.v
        if (v.t == 'dtStart') searchKey.left_date = v.v
        if (v.t == 'dtEnd') searchKey.right_date = v.v
      })
      paging.index = 1
      getDevice()
    }

    // 编辑设备信息、查看设备详情
    let DEV_DETAIL = ref(null)
    let DEV_DLG = ref(null)
    let devInfo = ref({name: ''})
    function handleBtn(index,row,f) {
      //console.log(index, row)
      let bd = getBatchData()
      let l = bd.length
      // if (l > 0) {
      //   ElNotification({
      //     type: 'warning',
      //     title: '当前已选中'+l+'条记录',
      //     message: '选中多条数据请使用批量处理'
      //   })
      //   return
      // }
      row.flag = f
      devInfo.value = row
      if (f == 'detail') {
        DEV_DETAIL.value.open(devInfo.value)
      } else if (util.hasStr('uninstall,autorun',f)) {
        let e = {}
        e.flag = f
        e.data = []
        e.data.push(row)
        BATCH_DLG.value.open(e)
      } else {
        DEV_DLG.value.open(devInfo.value)
      } 
    }
    // 批量处理设备信息
    let BATCH_DLG = ref(null)
    function handleBatch(f) {
      let bd = getBatchData()
      if (batchData.length < bd.length) batchData = bd
      let e = {}
      e.flag = util.hasStr('uninstall,autorun',f)?f:devPage.flag
      e.data = batchData
      BATCH_DLG.value.open(e)
    } 
    // 设备信息编辑完成
    function deviceDone(e) {      
      setTimeout(()=>{
        getDevice()
      },1)  
    }
    // batch data
    function setBatchData(e) {
      if (devPage.flag == 'device_factory') sessionStorage.setItem('dBatchData1',JSON.stringify(e))
      if (devPage.flag == 'device_list') sessionStorage.setItem('dBatchData2',JSON.stringify(e))
      if (devPage.flag == 'device_app') sessionStorage.setItem('dBatchData3',JSON.stringify(e))
      if (devPage.flag == 'device_system') sessionStorage.setItem('dBatchData4',JSON.stringify(e))
      if (devPage.flag == 'device_reset') sessionStorage.setItem('dBatchData5',JSON.stringify(e))
    }
    function getBatchData() {
      let bd = batchData
      if (devPage.flag == 'device_factory') bd = JSON.parse(sessionStorage.getItem('dBatchData1')) || []
      if (devPage.flag == 'device_list') bd = JSON.parse(sessionStorage.getItem('dBatchData2')) || []
      if (devPage.flag == 'device_app') bd = JSON.parse(sessionStorage.getItem('dBatchData3')) || []
      if (devPage.flag == 'device_system') bd = JSON.parse(sessionStorage.getItem('dBatchData4')) || []
      if (devPage.flag == 'device_reset') bd = JSON.parse(sessionStorage.getItem('dBatchData5')) || []
      return bd
    }

    function isNull(v) {
      return util.isNull(v)
    }

    return{
      user, devPage, deviceList, loading, handleSelectionChange, PAGING_COM, paging, pageChange, searchKey, searchDone,
      DEV_DETAIL, DEV_DLG, devInfo, handleBtn, BATCH_DLG, handleBatch, deviceDone,
      isNull
    }
  },
}
</script>

<style lang="scss" scoped src="./tab_content.scss"></style>